package main

import (
	"fmt"
	"log"
	"net/http"

	"gogo"
)

func main() {
	// 创建路由处理器
	router := gogo.NewHttpRouterHandler()

	// ===================
	// 默认主机路由（向后兼容）
	// ===================
	router.RegHTTPProcFunc("GET", "/", func(ctx *gogo.HTTPContext) {
		// 使用原始Host头（可能包含端口），但显示时会自动处理
		hostWithPort := ctx.GetRequest().Host
		ctx.WriteString(`
<!DOCTYPE html>
<html>
<head>
    <title>GoGo 主机名路由示例</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .host { background: #f0f8ff; padding: 20px; margin: 20px 0; border-radius: 8px; }
        .api { background: #f0fff0; padding: 20px; margin: 20px 0; border-radius: 8px; }
        .admin { background: #fff0f0; padding: 20px; margin: 20px 0; border-radius: 8px; }
        .static { background: #fffff0; padding: 20px; margin: 20px 0; border-radius: 8px; }
    </style>
</head>
<body>
    <h1>🌐 GoGo 主机名路由示例</h1>
    <p>当前访问地址: <strong>` + hostWithPort + `</strong></p>
    <p><em>注意：路由匹配时会自动去掉端口号，以主机名进行匹配</em></p>
    
    <div class="host">
        <h2>📍 默认主机 (任意域名)</h2>
        <p>您正在访问默认主机路由。这是一个通用的路由配置。</p>
        <ul>
            <li><a href="/">首页</a> - 当前页面</li>
            <li><a href="/about">关于页面</a></li>
        </ul>
    </div>

    <div class="api">
        <h2>🔗 测试不同主机名路由</h2>
        <p>请修改系统hosts文件，添加以下记录：</p>
        <pre>127.0.0.1 api.localhost
127.0.0.1 admin.localhost  
127.0.0.1 static.localhost</pre>
        <p>然后访问以下链接测试（注意：端口号会自动处理）：</p>
        <ul>
            <li><a href="http://api.localhost:3009/">API服务</a></li>
            <li><a href="http://admin.localhost:3009/">管理后台</a></li>
            <li><a href="http://static.localhost:3009/">静态文件服务</a></li>
        </ul>
    </div>
</body>
</html>`)
	})

	router.RegHTTPProcFunc("GET", "/about", func(ctx *gogo.HTTPContext) {
		ctx.WriteString(`
<!DOCTYPE html>
<html>
<head>
    <title>关于 - 默认主机</title>
</head>
<body>
    <h1>关于页面 - 默认主机</h1>
    <p>这是默认主机的关于页面。</p>
    <p>当前主机: ` + ctx.GetRequest().Host + `</p>
    <a href="/">返回首页</a>
</body>
</html>`)
	})

	// ===================
	// API域名路由 (api.localhost)
	// ===================
	router.RegHTTPProcFuncWithHost("api.localhost", "GET", "/", func(ctx *gogo.HTTPContext) {
		ctx.WriteJSON(map[string]interface{}{
			"service": "API Gateway",
			"version": "v1.0.0",
			"host":    ctx.GetRequest().Host,
			"message": "Welcome to API service",
			"endpoints": []string{
				"GET /users - 获取用户列表",
				"POST /users - 创建用户",
				"GET /users/:id - 获取单个用户",
				"PUT /users/:id - 更新用户",
				"DELETE /users/:id - 删除用户",
			},
		})
	})

	// API用户相关路由
	router.RegHTTPProcFuncWithHost("api.localhost", "GET", "/users", func(ctx *gogo.HTTPContext) {
		ctx.WriteJSON([]map[string]interface{}{
			{"id": 1, "name": "Alice", "email": "alice@example.com"},
			{"id": 2, "name": "Bob", "email": "bob@example.com"},
			{"id": 3, "name": "Charlie", "email": "charlie@example.com"},
		})
	})

	router.RegHTTPProcFuncWithHost("api.localhost", "GET", "/users/:id", func(ctx *gogo.HTTPContext) {
		id := ctx.GetPathParam(":id")
		ctx.WriteJSON(map[string]interface{}{
			"id":    id,
			"name":  "User " + id,
			"email": fmt.Sprintf("user%s@example.com", id),
			"host":  ctx.GetRequest().Host,
		})
	})

	router.RegHTTPProcFuncWithHost("api.localhost", "POST", "/users", func(ctx *gogo.HTTPContext) {
		body := ctx.GetPostBody()
		ctx.WriteJSON(map[string]interface{}{
			"message": "User created successfully",
			"data":    string(body),
			"host":    ctx.GetRequest().Host,
		})
	})

	// API的404页面
	router.RegHTTPStatusFuncWithHost("api.localhost", http.StatusNotFound, func(ctx *gogo.HTTPContext) {
		ctx.WriteHeaderStatus(http.StatusNotFound)
		ctx.WriteJSON(map[string]interface{}{
			"error":   "API endpoint not found",
			"host":    ctx.GetRequest().Host,
			"path":    ctx.GetRequest().URL.Path,
			"message": "Please check API documentation",
		})
	})

	// ===================
	// 管理后台域名路由 (admin.localhost)
	// ===================
	router.RegHTTPProcFuncWithHost("admin.localhost", "GET", "/", func(ctx *gogo.HTTPContext) {
		ctx.WriteString(`
<!DOCTYPE html>
<html>
<head>
    <title>管理后台</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; background: #f5f5f5; }
        .admin-panel { background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .nav { background: #333; color: white; padding: 15px; margin: -30px -30px 20px -30px; border-radius: 10px 10px 0 0; }
        .nav a { color: #4CAF50; text-decoration: none; margin-right: 20px; }
        .stats { display: flex; gap: 20px; margin: 20px 0; }
        .stat { background: #e3f2fd; padding: 20px; border-radius: 8px; flex: 1; text-align: center; }
    </style>
</head>
<body>
    <div class="admin-panel">
        <div class="nav">
            <h1>🛠️ 管理后台</h1>
            <a href="/">仪表盘</a>
            <a href="/users">用户管理</a>
            <a href="/settings">系统设置</a>
        </div>
        
        <h2>仪表盘</h2>
        <p>当前主机: <strong>` + ctx.GetRequest().Host + `</strong></p>
        
        <div class="stats">
            <div class="stat">
                <h3>👥 用户总数</h3>
                <div style="font-size: 24px; color: #1976d2;">1,234</div>
            </div>
            <div class="stat">
                <h3>📊 今日访问</h3>
                <div style="font-size: 24px; color: #1976d2;">5,678</div>
            </div>
            <div class="stat">
                <h3>💰 收入</h3>
                <div style="font-size: 24px; color: #1976d2;">¥12,345</div>
            </div>
        </div>
    </div>
</body>
</html>`)
	})

	router.RegHTTPProcFuncWithHost("admin.localhost", "GET", "/users", func(ctx *gogo.HTTPContext) {
		ctx.WriteString(`
<!DOCTYPE html>
<html>
<head>
    <title>用户管理 - 管理后台</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; background: #f5f5f5; }
        .admin-panel { background: white; padding: 30px; border-radius: 10px; }
        .nav { background: #333; color: white; padding: 15px; margin: -30px -30px 20px -30px; }
        .nav a { color: #4CAF50; text-decoration: none; margin-right: 20px; }
        table { width: 100%; border-collapse: collapse; margin: 20px 0; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <div class="admin-panel">
        <div class="nav">
            <h1>👥 用户管理</h1>
            <a href="/">仪表盘</a>
            <a href="/users">用户管理</a>
            <a href="/settings">系统设置</a>
        </div>
        
        <h2>用户列表</h2>
        <p>主机: ` + ctx.GetRequest().Host + `</p>
        
        <table>
            <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>邮箱</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            <tr>
                <td>1</td>
                <td>admin</td>
                <td>admin@example.com</td>
                <td>✅ 激活</td>
                <td>编辑 | 删除</td>
            </tr>
            <tr>
                <td>2</td>
                <td>user1</td>
                <td>user1@example.com</td>
                <td>✅ 激活</td>
                <td>编辑 | 删除</td>
            </tr>
        </table>
    </div>
</body>
</html>`)
	})

	// 管理后台的404页面
	router.RegHTTPStatusFuncWithHost("admin.localhost", http.StatusNotFound, func(ctx *gogo.HTTPContext) {
		ctx.WriteHeaderStatus(http.StatusNotFound)
		ctx.WriteString(`
<!DOCTYPE html>
<html>
<head>
    <title>页面未找到 - 管理后台</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; text-align: center; }
        .error { background: #ffebee; padding: 40px; border-radius: 10px; color: #c62828; }
    </style>
</head>
<body>
    <div class="error">
        <h1>🚫 404 - 页面未找到</h1>
        <p>抱歉，管理后台中未找到您访问的页面。</p>
        <p>主机: ` + ctx.GetRequest().Host + `</p>
        <p>路径: ` + ctx.GetRequest().URL.Path + `</p>
        <a href="/">返回仪表盘</a>
    </div>
</body>
</html>`)
	})

	// ===================
	// 静态文件域名路由 (static.localhost)
	// ===================
	router.RegHTTPProcFuncWithHost("static.localhost", "GET", "/", func(ctx *gogo.HTTPContext) {
		ctx.WriteString(`
<!DOCTYPE html>
<html>
<head>
    <title>静态文件服务</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .file-server { background: #fffaf0; padding: 30px; border-radius: 10px; border: 2px solid #ffd700; }
    </style>
</head>
<body>
    <div class="file-server">
        <h1>📁 静态文件服务</h1>
        <p>当前主机: <strong>` + ctx.GetRequest().Host + `</strong></p>
        
        <h2>可用文件：</h2>
        <ul>
            <li><a href="/demo.txt">demo.txt</a> - 示例文本文件</li>
            <li><a href="/info.json">info.json</a> - JSON信息文件</li>
            <li><a href="/style.css">style.css</a> - CSS样式文件</li>
        </ul>
        
        <p><strong>注意：</strong> 这是静态文件专用域名服务。</p>
    </div>
</body>
</html>`)
	})

	// 模拟静态文件
	router.RegHTTPProcFuncWithHost("static.localhost", "GET", "/demo.txt", func(ctx *gogo.HTTPContext) {
		ctx.GetR().Header.Set("Content-Type", "text/plain")
		ctx.WriteString(`这是一个示例文本文件
主机: ` + ctx.GetRequest().Host + `
时间: ` + fmt.Sprintf("%v", ctx.GetRequest().Header.Get("Date")) + `

GoGo框架支持基于主机名的路由分离！`)
	})

	router.RegHTTPProcFuncWithHost("static.localhost", "GET", "/info.json", func(ctx *gogo.HTTPContext) {
		ctx.WriteJSON(map[string]interface{}{
			"service":     "Static File Server",
			"host":        ctx.GetRequest().Host,
			"description": "专门提供静态文件服务的域名",
			"features": []string{
				"文件下载",
				"缓存优化",
				"压缩传输",
				"CDN加速",
			},
		})
	})

	router.RegHTTPProcFuncWithHost("static.localhost", "GET", "/style.css", func(ctx *gogo.HTTPContext) {
		ctx.GetR().Header.Set("Content-Type", "text/css")
		ctx.WriteString(`/* GoGo静态文件服务样式 */
body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #333;
}

.container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    background: rgba(255,255,255,0.95);
    border-radius: 15px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}

/* 主机名: ` + ctx.GetRequest().Host + ` */`)
	})

	// ===================
	// 默认404页面
	// ===================
	router.RegHTTPStatusFunc(http.StatusNotFound, func(ctx *gogo.HTTPContext) {
		ctx.WriteHeaderStatus(http.StatusNotFound)
		ctx.WriteString(`
<!DOCTYPE html>
<html>
<head>
    <title>页面未找到</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; text-align: center; }
        .error { background: #f0f0f0; padding: 40px; border-radius: 10px; }
    </style>
</head>
<body>
    <div class="error">
        <h1>🔍 404 - 页面未找到</h1>
        <p>抱歉，未找到您访问的页面。</p>
        <p>主机: ` + ctx.GetRequest().Host + `</p>
        <p>路径: ` + ctx.GetRequest().URL.Path + `</p>
        <a href="/">返回首页</a>
    </div>
</body>
</html>`)
	})

	// 使用自定义路由处理器启动服务
	log.Println("🚀 GoGo主机名路由示例服务器启动中...")
	log.Println("📍 请访问: http://localhost:3009")
	log.Println("🔧 配置hosts文件测试不同域名:")
	log.Println("   127.0.0.1 api.localhost")
	log.Println("   127.0.0.1 admin.localhost")
	log.Println("   127.0.0.1 static.localhost")
	log.Println()
	log.Println("🌐 测试URL:")
	log.Println("   http://localhost:3009/ (默认主机)")
	log.Println("   http://api.localhost:3009/ (API服务)")
	log.Println("   http://admin.localhost:3009/ (管理后台)")
	log.Println("   http://static.localhost:3009/ (静态文件)")

	// 启动HTTP服务，使用自定义路由处理器
	server := &http.Server{
		Addr: ":3009",
	}
	server.Handler = router
	if err := server.ListenAndServe(); err != nil {
		log.Fatalf("启动http服务失败: %v", err)
	}
}
